"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : dolphin
Case Name   : 含dolphin插件库下执行gs_probackup全量备份和增量备份
Create At   : 2022.04.06
Owner       : z@wan005
Description :
    1、创建b库和用户
    2、b库下查询dolphin插件
    3、进行初始化
    4、添加实例
    5、全量备份
    6、增量备份
    7、查询备份状态
    8、清理环境
Expect      :
    1、成功
    2、自动加载成功,无需手动创建
    3、成功
    4、成功
    5、成功
    6、成功
    7、成功
    8、清理环境完成
History     :modified by z@wan005,2022.08.29，om数据库目前实现自动加载dolphin插件，
             因此删除用例中拷贝插件依赖文件步骤
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class PluginTest04(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.common = Common()
        self.sh_primy = CommonSH('PrimaryDbUser')
        self.user_node = Node('PrimaryDbUser')
        self.constant = Constant()
        self.parent_path = os.path.dirname(macro.DB_INSTANCE_PATH)
        self.gs_probackup_path = os.path.join(self.parent_path,
                                              'gs_probackup_testdir0004')
        self.db_name = 'db_plugin0004'
        self.us_name = 'us_plugin0004'
        self.default_value = self.common.show_param('enable_cbm_tracking')
        guc_cmd = self.sh_primy.execute_gsguc('reload',
                                              self.constant.GSGUC_SUCCESS_MSG,
                                              'enable_cbm_tracking=on',
                                              single=True)
        self.log.info(guc_cmd)

    def test_dolphin(self):
        text = '----step1:创建b库和用户;expect:成功----'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.db_name};" \
                  f"create database {self.db_name} DBCOMPATIBILITY ='B';" \
                  f"drop user if exists {self.us_name};" \
                  f"create user {self.us_name} with sysadmin " \
                  f"password '{macro.COMMON_PASSWD}';"
        self.log.info(sql_cmd)
        sql_res = self.sh_primy.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, sql_res,
                      '执行失败' + text)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, sql_res,
                      '执行失败' + text)

        text = '---step2:b库下查询dolphin插件;expect:自动加载成功,无需手动创建---'
        self.log.info(text)
        sql_cmd = "select extname from pg_extension where extname ='dolphin';"
        self.log.info(sql_cmd)
        sql_res = self.sh_primy.execut_db_sql(sql_cmd, dbname=self.db_name)
        self.log.info(sql_res)
        self.assertEqual('dolphin', sql_res.splitlines()[-2].strip(),
                         '执行失败' + text)

        text = '--step3:进行初始化;expect:初始化成功---'
        self.log.info(text)
        init_cmd = f"source {macro.DB_ENV_PATH};" \
                   f"gs_probackup init -B {self.gs_probackup_path};"
        self.log.info(init_cmd)
        init_msg = self.user_node.sh(init_cmd).result()
        self.log.info(init_msg)
        self.assertIn(self.constant.init_success, init_msg,
                      '执行失败:' + text)

        text = '-----step4:添加实例;expect:成功---'
        self.log.info(text)
        add_cmd = f"source {macro.DB_ENV_PATH};" \
                  f"gs_probackup add-instance -B {self.gs_probackup_path} " \
                  f"-D {macro.DB_INSTANCE_PATH} --instance=pro1 ;"
        self.log.info(add_cmd)
        add_msg = self.user_node.sh(add_cmd).result()
        self.log.info(add_msg)
        self.assertIn("'pro1' " + self.constant.init_success, add_msg,
                      '执行失败:' + text)

        text = '-----step5:全量备份;expect:成功---'
        self.log.info(text)
        bak_cmd = f"source {macro.DB_ENV_PATH};" \
                  f"gs_probackup backup -B {self.gs_probackup_path} " \
                  f"-b full --stream  --instance=pro1  " \
                  f"-U  {self.us_name} -d {self.db_name} " \
                  f"-p {self.user_node.db_port} " \
                  f"-W {macro.COMMON_PASSWD};"
        self.log.info(bak_cmd)
        bak_msg = self.user_node.sh(bak_cmd).result()
        self.log.info(bak_msg)
        self.assertIn('completed', bak_msg, '执行失败:' + text)

        text = '-----step6:增量备份;expect:成功---'
        self.log.info(text)
        bak_cmd = f"source {macro.DB_ENV_PATH};" \
                  f"gs_probackup backup -B {self.gs_probackup_path} " \
                  f"-b PTRACK --stream  --instance=pro1  " \
                  f"-U  {self.us_name} -d {self.db_name} " \
                  f"-p {self.user_node.db_port} " \
                  f"-W {macro.COMMON_PASSWD};"
        self.log.info(bak_cmd)
        bak_msg = self.user_node.sh(bak_cmd).result()
        self.log.info(bak_msg)
        self.assertIn('completed', bak_msg, '执行失败:' + text)

        text = '-----step7:查询备份状态;expect:成功---'
        self.log.info(text)
        show_cmd = f"source {macro.DB_ENV_PATH};" \
                   f"gs_probackup show -B {self.gs_probackup_path};"
        self.log.info(show_cmd)
        show_msg = self.user_node.sh(show_cmd).result()
        self.log.info(show_msg)
        self.assertTrue(show_msg.count('OK') == 2, '执行失败:' + text)

    def tearDown(self):
        text = '--step8:清理环境;expect:清理环境完成--'
        self.log.info(text)
        guc_cmd = self.sh_primy.execute_gsguc('reload',
                                              self.constant.GSGUC_SUCCESS_MSG,
                                              f'enable_cbm_tracking'
                                              f'={self.default_value}',
                                              single=True)
        self.log.info(guc_cmd)
        sql_cmd = f"drop database if exists {self.db_name};" \
                  f"drop user if exists {self.us_name};"
        self.log.info(sql_cmd)
        sql_res = self.sh_primy.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        rm_cmd1 = self.user_node.sh(
            f"rm -rf {self.gs_probackup_path}").result()
        self.log.info(rm_cmd1)
        self.log.info('断言teardown成功')
        self.assertTrue(guc_cmd, '执行失败:' + text)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, sql_res,
                      '执行失败' + text)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, sql_res,
                      '执行失败' + text)
        self.assertEqual(len(rm_cmd1), 0, '执行失败:' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
